package org.bing.engine.controller.service;

import java.util.ArrayList;
import java.util.List;

import org.bing.engine.controller.preference.PreferenceManager;
import org.bing.engine.core.domain.Console;
import org.bing.engine.core.domain.ContainerInstance;
import org.bing.engine.core.domain.Controller;
import org.bing.engine.core.domain.ControllerGroup;

public class LocalInstanceManager {
    private List<ContainerInstance> list = new ArrayList<ContainerInstance>();
    protected PreferenceManager preference;
    private LocalControllerManager controllerManager;
    private Controller controller;

    public void setPreferenceManager(PreferenceManager mgr) {
        this.preference = mgr;
    }

    public void setControllerManager(LocalControllerManager mgr) {
        controllerManager = mgr;
    }

    public synchronized void init() {
        // query console/group
        Console console = preference.getTargetConsole();
        ControllerGroup group = preference.getTargetGroup();
        if (console != null && group != null) {
            Controller controller = controllerManager.localController();
            save(controller);
        }
        List<ContainerInstance> inst = preference.getContainerInstance();
        if (inst != null) {
            this.list = inst;
        }
    }

    public synchronized void save(Controller controller) {
        this.controller = controller;
    }

    public synchronized void save(ContainerInstance inst) {
        String guid = inst.getGlobalId();
        for (ContainerInstance inst2 : list) {
            if (guid.equals(inst2.getGlobalId())) {
                return;
            }
        }
        list.add(inst);
        preference.saveContainerInstance(list);
    }

    public synchronized void delete(ContainerInstance inst) {
        String guid = inst.getGlobalId();
        for (int i = 0; i < list.size(); i++) {
            ContainerInstance inst2 = list.get(i);
            if (guid.equals(inst2.getGlobalId())) {
                list.remove(i);
                break;
            }
        }
        preference.saveContainerInstance(list);
    }

    public synchronized List<ContainerInstance> findAllContainerInstance() {
        // concurrent error,so copy list to client
        return new ArrayList<ContainerInstance>(list);
    }

    public synchronized Controller findController() {
        return controller;
    }
}
